import request from "../../utils/request";

Page({
    data: {
        userInfo: {},  // 用户信息对象，默认空
    },

    onLoad() {
        // 页面加载时尝试从缓存读取用户信息
        const userInfo = wx.getStorageSync('userInfo');
        if (userInfo) {
            this.setData({userInfo});
        }
    },

    // 点击头像区域触发登录
    handleLogin() {
        // 获取用户信息的新版接口，弹窗请求用户授权
        wx.getUserProfile({
            desc: '用于完善会员资料',
            success: (res) => {
                // res.userInfo 包含昵称、头像等信息
                this.setData({userInfo: res.userInfo});

                // 缓存用户信息，方便下次自动读取
                wx.setStorageSync('userInfo', res.userInfo);
            },
            fail: () => {
                wx.showToast({title: '授权失败，请重试', icon: 'error'});
            }
        });
    },

    // 下面是菜单跳转示例（你的菜单事件绑定函数）
    goToProfile() {
        wx.navigateTo({url: '/pages/profile/index'});
    },

    goToRecords() {
        wx.navigateTo({url: '/pages/records/index'});
    },


    openPhoneModal() {
        this.setData({ showPhoneModal: true });
    },

    closePhoneModal() {
        this.setData({ showPhoneModal: false, newPhone: '' });
    },

    onPhoneInput(e) {
        this.setData({ newPhone: e.detail.value });
    },

    confirmPhoneChange() {
        const phone = this.data.newPhone.trim();

        // 简单校验
        if (!/^1\d{10}$/.test(phone)) {
            wx.showToast({ title: '请输入正确手机号', icon: 'none' });
            return;
        }

        // 模拟请求
        this.setData({
            phone,
            showPhoneModal: false,
            newPhone: ''
        });

        wx.showToast({ title: '修改成功', icon: 'success' });
    },




    goToSettings() {
        let userInfo = wx.getStorageSync('userInfo')
        //获取code
        wx.login({
            success: (res) =>
                //获取缓存用户信息
                //请求配置接口
                request.fetch({
                    url: '/api/login/index', method: 'POST', data: {
                        code: res.code,
                        platform: 1,
                        avatar: userInfo.avatarUrl,
                        nickname: userInfo.nickName,
                    }
                }).then(res => {
                   //判断结果
                    if (res.code === 1) {
                        app.globalData.accessToken = res.data.token
                    }


                })

        });

    }
});
